package Twx0429;

import java.io.*;
import java.nio.file.*;
import java.nio.file.Path;
import java.util.ArrayList;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class UserStorage {

    private static final String DATA_FILE = "users.txt";
    private  String Temp = "temp.txt";

    private String userToText(User user){
        return user.getName() + ":" + user.getPwd() + ":" + user.isIsLogin();
    }

    private User textToUser(String text){
        String[] parts = text.split(":");
        if (parts.length != 3){
            return null;
        }
        return new User(parts[0], parts[1], Boolean.parseBoolean(parts[2]));
    }

    public void saveUsers(List<User> users){
        try(BufferedWriter writer = new BufferedWriter(new FileWriter(DATA_FILE,true))){
            for(User user : users){
                writer.write(userToText(user));
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<User> loadUsers(){
        List<User> users = new ArrayList<>();
        try(BufferedReader reader = new BufferedReader(new FileReader(DATA_FILE))){
            String line;
            while ((line = reader.readLine()) != null){
                users.add(textToUser(line));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return users;
    }

    public void changeUsers(String name){
        Path originalFile = Paths.get(DATA_FILE);
        Path tempFile = Paths.get(Temp);

        try(BufferedReader load = new BufferedReader(new FileReader(DATA_FILE));
        BufferedWriter change = new BufferedWriter(new FileWriter(Temp))){
            String temp ;
            int lineNumber = 0;
            while ((temp = load.readLine()) != null){
                String[] p = temp.split(":");
                lineNumber++;
                if (name.equals(p[0])){
                    p[2] = "True";
                    temp = p[0] + ":" + p[1] + ":" + p[2];
                }
                change.write(temp);
                change.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            Files.move(tempFile, originalFile, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e){
            e.printStackTrace();
        }
    }

}
